import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Commit提交模板
 */
public class CT extends Application {

    private TextField numberField, messageField, userField;
    private TextArea previewArea;
    private static final String ID_PREFIX = "US";

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Commit模板生成器");
        primaryStage.setWidth(600);
        primaryStage.setHeight(500);

        // 创建主布局
        BorderPane root = new BorderPane();
        root.setPadding(new Insets(10));

        // 表单区域
        GridPane formPane = createFormPane();
        root.setTop(formPane);

        // 预览区域
        previewArea = new TextArea();
        previewArea.setEditable(false);
        previewArea.setWrapText(true);
        previewArea.setFont(Font.font("Monospaced", 12));
        root.setCenter(previewArea);

        // 按钮区域
        HBox buttonBox = createButtonBox();
        root.setBottom(buttonBox);

        // 初始化预览
        updatePreview();

        // 创建场景
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private GridPane createFormPane() {
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(10));

        // 编号输入
        Label numberLabel = new Label("当前编号:");
        numberField = new TextField();
        numberField.setPromptText("请输入编号");
        numberField.textProperty().addListener(new javafx.beans.value.ChangeListener<String>() {
            @Override
            public void changed(javafx.beans.value.ObservableValue<? extends String> observable,
                                String oldValue, String newValue) {
                if (!newValue.matches("\\d*")) {
                    numberField.setText(newValue.replaceAll("[^\\d]", ""));
                }
                updatePreview();
            }
        });

        // 消息输入
        Label messageLabel = new Label("提交信息:");
        messageField = new TextField();
        messageField.setPromptText("简要描述修改内容");
        messageField.textProperty().addListener(new javafx.beans.value.ChangeListener<String>() {
            @Override
            public void changed(javafx.beans.value.ObservableValue<? extends String> observable,
                                String oldValue, String newValue) {
                updatePreview();
            }
        });

        // 用户输入
        Label userLabel = new Label("提交人:");
        userField = new TextField();
        userField.setPromptText("输入您的名字");
        userField.setText(System.getProperty("user.name"));
        userField.textProperty().addListener(new javafx.beans.value.ChangeListener<String>() {
            @Override
            public void changed(javafx.beans.value.ObservableValue<? extends String> observable,
                                String oldValue, String newValue) {
                updatePreview();
            }
        });

        // 添加到网格
        grid.add(numberLabel, 0, 0);
        grid.add(numberField, 1, 0);
        grid.add(messageLabel, 0, 1);
        grid.add(messageField, 1, 1);
        grid.add(userLabel, 0, 2);
        grid.add(userField, 1, 2);

        return grid;
    }

    private HBox createButtonBox() {
        HBox buttonBox = new HBox(10);
        buttonBox.setPadding(new Insets(10));
        buttonBox.setAlignment(javafx.geometry.Pos.CENTER);

        // 生成按钮
        Button generateButton = new Button("生成模板");
        generateButton.setOnAction(new javafx.event.EventHandler<javafx.event.ActionEvent>() {
            @Override
            public void handle(javafx.event.ActionEvent event) {
                updatePreview();
            }
        });

        // 复制按钮
        Button copyButton = new Button("复制到剪贴板");
        copyButton.setOnAction(new javafx.event.EventHandler<javafx.event.ActionEvent>() {
            @Override
            public void handle(javafx.event.ActionEvent event) {
                copyToClipboard();
            }
        });

        // 清空按钮
        Button clearButton = new Button("清空");
        clearButton.setOnAction(new javafx.event.EventHandler<javafx.event.ActionEvent>() {
            @Override
            public void handle(javafx.event.ActionEvent event) {
                clearFields();
            }
        });

        buttonBox.getChildren().addAll(generateButton, copyButton, clearButton);
        return buttonBox;
    }

    private void updatePreview() {
        String number = numberField.getText().trim();
        String message = messageField.getText().trim();
        String user = userField.getText().trim();

        if (number.isEmpty() || message.isEmpty() || user.isEmpty()) {
            previewArea.setText("请填写完整信息...");
            return;
        }

        LocalDateTime date = LocalDateTime.now();
        String id = ID_PREFIX + date.getYear() + number;
        String formattedDate = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        StringBuilder template = new StringBuilder();
        template.append(String.format("%-12s %s%n", "id:", id));
        template.append(String.format("%-12s %s%n", "message:", message));
        template.append(String.format("%-12s %s%n", "commitUser:", user));
        template.append(String.format("%-12s %s%n", "commitDate:", formattedDate));

        previewArea.setText(template.toString());
    }

    private void copyToClipboard() {
        String content = previewArea.getText();
        if (content.isEmpty() || content.equals("请填写完整信息...")) {
            showAlert("错误", "没有可复制的内容");
            return;
        }

        javafx.scene.input.Clipboard clipboard = javafx.scene.input.Clipboard.getSystemClipboard();
        javafx.scene.input.ClipboardContent clipboardContent = new javafx.scene.input.ClipboardContent();
        clipboardContent.putString(content);
        clipboard.setContent(clipboardContent);

        showAlert("成功", "模板已复制到剪贴板");
    }

    private void clearFields() {
        numberField.clear();
        messageField.clear();
        userField.setText(System.getProperty("user.name"));
        updatePreview();
    }

    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    // Java 8 需要显式定义 Alert 类
    static class Alert {
        public enum AlertType { INFORMATION, ERROR }

        private AlertType type;
        private String title;
        private String headerText;
        private String contentText;

        public Alert(AlertType type) {
            this.type = type;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public void setHeaderText(String headerText) {
            this.headerText = headerText;
        }

        public void setContentText(String contentText) {
            this.contentText = contentText;
        }

        public void showAndWait() {
            // 使用 JavaFX 的 Alert 类
            javafx.scene.control.Alert fxAlert = new javafx.scene.control.Alert(
                    type == AlertType.INFORMATION ?
                            javafx.scene.control.Alert.AlertType.INFORMATION :
                            javafx.scene.control.Alert.AlertType.ERROR
            );
            fxAlert.setTitle(title);
            fxAlert.setHeaderText(headerText);
            fxAlert.setContentText(contentText);
            fxAlert.showAndWait();
        }
    }
}
